package cn.com.bluemoon.daps.model.service.impl;

import cn.com.bluemoon.daps.common.enums.BmStatus;
import cn.com.bluemoon.daps.model.entity.DapDataModelSystemTagMiddle;
import cn.com.bluemoon.daps.model.mapper.DapDataModelSystemTagMiddleMapper;
import cn.com.bluemoon.daps.model.service.DapDataModelSystemTagMiddleService;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;

/**
 * <p>
 * 数据模型-关联标签的中间表 服务实现类
 * </p>
 *
 * @author admin
 * @since 2020-08-03
 */
@Slf4j
@Service
@Transactional
public class DapDataModelSystemTagMiddleServiceImpl extends ServiceImpl<DapDataModelSystemTagMiddleMapper, DapDataModelSystemTagMiddle> implements DapDataModelSystemTagMiddleService {

    @Autowired
    DapDataModelSystemTagMiddleMapper dapDataModelSystemTagMiddleMapper;

    /**
     * 新增模型或模型表引用标签数据
     * @param tagIds
     * @param modelId
     * @param relType
     * @return
     */
    @Override
    public Boolean insertModelTag(List<String> tagIds, String modelId, int relType) {

        List<DapDataModelSystemTagMiddle> list = new ArrayList<>();
        tagIds.forEach(id ->{
            DapDataModelSystemTagMiddle dm = new DapDataModelSystemTagMiddle();
            dm.setRelDataId(modelId);
            dm.setRelType(relType);
            dm.setSystemTagId(id);
            list.add(dm);
        });
        return this.saveBatch(list);
    }

    /**
     * 根据模型id去删除已存在的数据
     * @param modelId
     * @return
     */
    @Override
    public int updateModelTag( String modelId, Integer relType) {

        int i = dapDataModelSystemTagMiddleMapper.updateByDataId(modelId, relType);
        return i;
    }

    /**
     * 用于判断标签是否被其他系统引用
     * @param tagId
     * @return
     */
    @Override
    public List<DapDataModelSystemTagMiddle> getListByTagId(String tagId) {

        List<DapDataModelSystemTagMiddle> dapDataModelSystemTagMiddles = dapDataModelSystemTagMiddleMapper.selectList(new QueryWrapper<DapDataModelSystemTagMiddle>().
                eq("system_tag_id", tagId).eq("bm_status", BmStatus.ON.getCode()));
        return dapDataModelSystemTagMiddles;
    }

    /**
     * 通过模型表id删除标签
     * @param ids
     * @return
     */
    @Override
    public void deleteTableTags(List<String> ids) {

        /*ids.forEach(id ->{
            dapDataModelSystemTagMiddleMapper.updateByDataId(id, 1);
        });*/
        for (String id : ids) {
            dapDataModelSystemTagMiddleMapper.updateByDataId(id, 1);
        }
    }
}
